package com.xuecheng.ucenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.ucenter.feignclient.CheckCodeClient;
import com.xuecheng.ucenter.mapper.XcUserMapper;
import com.xuecheng.ucenter.model.dto.AuthParamsDto;
import com.xuecheng.ucenter.model.dto.XcUserExt;
import com.xuecheng.ucenter.model.po.XcUser;
import com.xuecheng.ucenter.service.AuthService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * @ Author：祝文龙
 * @ Date：2023-11-28-20:46
 * @ Version：1.0
 * @ Description：账号密码认证
 */
@Service("password_authservice")
public class PasswordAuthServiceImpl implements AuthService {

    @Autowired
    XcUserMapper xcUserMapper;

    @Autowired
    PasswordEncoder passwordEncoder;

    @Autowired
    CheckCodeClient checkCodeClient;
    @Override
    public XcUserExt execute(AuthParamsDto authParamsDto) {



//        账号是否存在
        String username = authParamsDto.getUsername();

        String checkcode = authParamsDto.getCheckcode();

        String checkcodekey = authParamsDto.getCheckcodekey();
        if(StringUtils.isEmpty(checkcode)||StringUtils.isEmpty(checkcodekey)){
            throw  new RuntimeException("验证码不能为空!");
        }
        Boolean verify = checkCodeClient.verify(checkcodekey, checkcode);
        if(verify==null || !verify){
            throw new RuntimeException("验证码有误!");
        }
//        根据username账号查询数据库
        LambdaQueryWrapper<XcUser> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(XcUser::getUsername, username);
        XcUser xcUser = xcUserMapper.selectOne(queryWrapper);
//        查询到用户不存在,返回null   SpringSecurity框架就会抛出异常 用户不存在
        if (xcUser==null) {
           throw new RuntimeException("账号不存在!");
        }
//        校验密码是否正确
//      如果查到了用户,拿到正确的密码
        String passwordDb = xcUser.getPassword();
//        拿到用户输入的密码
        String passwordForm = authParamsDto.getPassword();
//        校验密码
        boolean matches = passwordEncoder.matches(passwordForm, passwordDb);
        if (!matches){
            throw new RuntimeException("账号或密码不正确!");
        }

        XcUserExt xcUserExt = new XcUserExt();

        BeanUtils.copyProperties(xcUser,xcUserExt);
        return xcUserExt;
    }
}
